package com.linxz.framework.protocol.Interceptors;

import com.linxz.utils.Logger;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * @author Linxz
 * 创建日期：2019年02月20日 20:02
 * version：1.0.0
 * 描述：
 */
public class LoggerInterceptor extends BaseInterceptor{
    @Override
    public Response intercept(Chain chain) throws IOException {
        return logger(chain);
    }

    private Response logger(Chain chain){
        Request originalRequest = chain.request();
        try {
            //请求url
            String requestURL = originalRequest.url().toString();
            Request request = originalRequest;
            Logger.log(requestURL);
            String method = originalRequest.method();
            final String POST="POST";
            if (POST.equals(method) && !requestURL.contains("/file/images") && !requestURL.contains("upload") && !requestURL.contains("uploadVideo")) {
                request=originalRequest;
                StringBuilder sb = new StringBuilder();
                if (originalRequest.body() instanceof FormBody) {
                    FormBody body = (FormBody) originalRequest.body();
                    for (int i = 0; i < body.size(); i++) {
                        sb.append(body.encodedName(i)).append("=").append(body.encodedValue(i)).append(",");
                    }
                    sb.delete(sb.length() - 1, sb.length());
                    Logger.log("| RequestParams:{" + sb.toString() + "}");
                } else {
                    Buffer buffer = new Buffer();
                    originalRequest.body().writeTo(buffer);
                    String oldParamsJson = buffer.readUtf8();
                    request = originalRequest;
                    Logger.log("| RequestParams:{" + oldParamsJson+ "}");
                }
            }
            //释放拦截，进行网络访问
            Response response = chain.proceed(request);
            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            Logger.log(content);
            return response.newBuilder()
                    .body(ResponseBody.create(mediaType, content))
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
